package pl.com.qapps.unity;

import java.io.IOException;

import pl.com.qapps.unity.AppIndicator.Category;
import pl.com.qapps.unity.UnityPb.IndicatorProperty;
import pl.com.qapps.unity.UnityPb.PropertyValue;
import pl.com.qapps.unity.UnityPb.RequestPb;
import pl.com.qapps.unity.UnityPb.RequestPb.Type;
import pl.com.qapps.unity.UnityPb.ResponsePb;
import pl.com.qapps.unity.UnityPb.ResponsePb.Status;

/**
 * @author Jakub Dykowski
 * 
 */
final class IndicatorProxy {

	private final Category category;
	private final String id;

	IndicatorProxy(String id, String iconName, Category category) {

		if (id == null)
			throw new IllegalArgumentException("id cannot be null");
		if (category == null)
			throw new IllegalArgumentException("category cannot be null");
		if (iconName == null)
			throw new IllegalArgumentException("iconName cannot be null");

		this.category = category;
		this.id = id;
	}

	Category getCategory() {
		return category;
	}

	String getId() {
		return id;
	}

	PropertyValue get(IndicatorProperty property) {
		ResponsePb res = send(RequestPb.newBuilder().setApp(id)
				.setType(Type.INDICATOR_GET).setIndicatorProperty(property)
				.build());
		if (!res.hasValue()) {
			// TODO make better exception handling
			throw new IndicatorException("internal error, no value returned");
		}
		return res.getValue();
	}

	void set(IndicatorProperty property, PropertyValue value) {
		send(RequestPb.newBuilder().setApp(id).setType(Type.INDICATOR_SET)
				.setIndicatorProperty(property).setValue(value).build());
	}

	private ResponsePb send(RequestPb req) {
		ResponsePb res;
		try {
			res = Unity.connect().send(req);
			if (res.getResult() == Status.FAILURE) {
				// TODO make better exception handling
				if (res.hasImpl()) {
					if (res.getImpl())
						throw new IndicatorException("Implementation error: "
								+ res.getErrorMessage(), res.getImpl());
					else
						throw new IndicatorException(res.getErrorMessage(),
								res.getImpl());
				}
				throw new IndicatorException(res.getErrorMessage());
			}
			return res;
		} catch (IllegalStateException | IOException e) {
			// TODO make better exception handling
			throw new LauncherException("failed to update item status", e);
		}
	}

}
